package base.thread.synchronizer;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * future futuretask
 * 
 * @author Administrator
 * 
 */
public class FutureTaskDemo {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void main(String[] args) {
		
		Callable callable = new PrivateAccount();
		FutureTask futureTask = new FutureTask(callable);

		Thread privateThread = new Thread(futureTask);
		System.out.println("future task starts at " + System.nanoTime());
		privateThread.start();
		System.out.println("main thread doing something else here. ");

		int totalMoney = new Random().nextInt(100000);
		System.out.println("you have " + totalMoney
				+ " in your other accounts.");
		System.out.println("waiting for data from privat Account");

		while (!futureTask.isDone()) {
			try {
				Thread.sleep(50);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println("future task ends at " + System.nanoTime());

		Integer privateAccountMoney = null;
		try {
			privateAccountMoney = (Integer) futureTask.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("the total money you have is "
				+ (totalMoney + privateAccountMoney.intValue()));
	}

}

@SuppressWarnings("rawtypes")
class PrivateAccount implements Callable {
	Integer privateTotalMoney;

	public Object call() throws Exception {
		Thread.sleep(5000);
		privateTotalMoney = new Integer(new Random().nextInt(10000));
		System.out.println("you have " + privateTotalMoney
				+ " in your private account");
		return privateTotalMoney;
	}
}
